<?php
namespace Sfsn\Core\Util;

use Sfsn\Core\Controller\Factory;
/**
 * // 分页类使用实例 1 将配置参数初始化时传入
 * $config = [
 * 'tag' => 'page',
 * 'separator' => '-',
 * 'nextPage' => '下一页',
 * 'prePage' => '上一页',
 * 'firstPage' => '首页',
 * 'lastPage' => '尾页',
 * 'preBar' => '<<',
 * 'nextBar' => '>>',
 * 'wrap' => '',
 * 'wrapClass' => 'pagewrap',
 * 'wrapId' => '',
 * 'isAjax' => false,
 * 'ajaxName' => '',
 * 'barNum' => 10,
 * 'total' => 50,
 * 'rows'=>10,
 * 'mode'=>1,
 * ];
 * $page = new Page($config);
 * $pagestring = $page->show();
 * echo $pagestring;
 * //分页类使用实例 2 初始化后设置属性
 * $page2 = new Page();
 * $page2->total = 50;
 * $pagestring = $page2->show();
 * echo $pagestring;
 * //获取数据
 * $cur_page = $page->getCurPage(); // 当前页码
 * $listRows = 10;
 * $limit_start = ($cur_page - 1) * $listRows;
 * $limit = $limit_start . ',' . $listRows;
 * Visit::limit($limit)->fetchAll();
 */
class Page
{

    /**
     * 配置数组
     *
     * @var unknown
     */
    public $config = [
        /**
         * 标签
         */
        'tag' => 'page',
        /**
         * 分隔符
         */
        'separator' => '-',
        
        /**
         * 下一页
         */
        'nextPage' => '下一页',
        
        /**
         * 上一页
         */
        'prePage' => '上一页',
        
        /**
         * 首页
         */
        'firstPage' => '首页',
        
        /**
         * 尾页
         */
        'lastPage' => '尾页',
        
        /**
         * 上一分页条
         */
        'preBar' => '<<',
        
        /**
         * 下一分页条
         */
        'nextBar' => '>>',
        
        /**
         * 分页字符串容器
         */
        'wrap' => '',
        
        /**
         * 分页字符串容器class
         */
        'wrapClass' => 'pagewrap',
        
        /**
         * 分页字符串容器的id
         */
        'wrapId' => '',
        
        /**
         * 是否支持AJAX分页模式
         */
        'isAjax' => false,
        
        /**
         * AJAX动作名
         */
        'ajaxName' => '',
        
        /**
         * 页码个数。
         */
        'barNum' => 10,
        
        /**
         * 记录条数
         */
        'total' => 0,
        
        /**
         * 每页显示条数
         */
        'rows' => 10,
        
        /**
         * 显示风格，参数可为整数1，2，3，4任意一个
         */
        'mode' => 1
    ];

    /**
     * 当前页
     * 
     * @var unknown
     */
    public $current = 0;

    /**
     * 总页数
     * 
     * @var unknown
     */
    public $totalPage = 0;

    /**
     * constructor构造函数
     *
     * @param $array['pageName'], $array['ajax']            
     */
    public function __construct($config = [])
    {
        // 配置初始化
        $this->config = array_merge($this->config, $config);
        //获取完整url
        $this->config['url'] = Factory::create('request')->getFullUrl();
    }

    public function __get($property)
    {
        return $this->config[$property];
    }

    public function __set($property, $value = null)
    {
        $this->config[$property] = $value;
    }

    /**
     * 获取显示"下一页"的代码
     *
     * @param string $style            
     * @return string
     */
    public function nextPage($style = 'nextPage')
    {
        if ($this->current < $this->totalPage) {
            $page = $this->current + 1;
            return $this->_getLink($page, $this->nextPage, $style);
        }
        return '';
    }

    /**
     * 获取显示“上一页”的代码
     *
     * @param string $style            
     * @return string
     */
    public function prePage($style = 'prePage')
    {
        if ($this->current > 1) {
            $page = $this->current - 1;
            return $this->_getLink($page, $this->prePage, $style);
        }
        return '';
    }

    /**
     * 获取显示“首页”的代码
     *
     * @return string
     */
    public function firstPage($style = 'firstPage')
    {
        if ($this->current == 1) {
            return '';
        }
        return $this->_getLink(1, $this->firstPage, $style);
    }

    /**
     * 获取显示“尾页”的代码
     *
     * @return string
     */
    public function lastPage($style = 'lastPage')
    {
        if ($this->current == $this->totalPage) {
            return '';
        }
        return $this->_getLink($this->totalPage, $this->lastPage, $style);
    }

    public function nowBar($style = 'page', $current = 'current')
    {
        $plus = ceil($this->barNum / 2);
        
        $begin = $this->current - $plus + 1;
        $begin = max($begin, 1);
        $end = $this->current + $plus;
        $end = min($end, $this->totalPage);
        $return = '';
        for ($i = $begin; $i <= $end; $i ++) {
            if ($i <= $end) {
                if ($i != $this->current) {
                    $return .= $this->_getLink($i, $i, $style);
                } else {
                    $return .= '<span class="' . $current . '">' . $i . '</span>';
                }
            } else {
                break;
            }
            $return .= " ";
        }
        return $return;
    }

    /**
     * 获取显示跳转按钮的代码
     *
     * @return string
     */
    public function select()
    {
        if ($this->totalPage > 1) {
            $return = '<select onChange="window.location=this.options[this.selectedIndex].value">';
            for ($i = 1; $i <= $this->totalPage; $i ++) {
                if ($i == $this->current) {
                    $return .= '<option value="' . $i . '" selected>' . $i . '</option>';
                } else {
                    $return .= '<option value="' . $this->_getUrl($i) . '">' . $i . '</option>';
                }
            }
            $return .= '</select>';
            return $return;
        }
    }

    /**
     * 控制分页显示风格（你可以增加相应的风格）
     */
    public function show()
    {
        $this->totalPage = ceil($this->total / $this->rows); // 计算总页数
                                                             
        // 获取到当前页,如果为0则执行获取方法
        $this->current == 0 && $this->getCurPage();
        
        $pageString = '';
        // 翻页小于1的 不显示页码
        if ($this->totalPage <= 1)
            return $pageString;
        switch ($this->mode) {
            case 1:
                $pageString = $this->firstPage() . $this->prePage() . $this->nowBar() . $this->nextPage() . $this->lastPage();
                break;
            case 2:
                $pageString = $this->firstPage() . $this->prePage() . '[第' . $this->current . '页]' . $this->nextPage() . $this->lastPage() . '第' . $this->select() . '页';
                break;
            case 3:
                $pageString = $this->firstPage() . $this->prePage() . $this->nextPage() . $this->lastPage();
                break;
            case 4:
                $pageString = $this->prePage() . $this->nowBar() . $this->nextPage();
                break;
            case 5:
                $pageString = $this->prePage() . $this->nowBar() . $this->nextPage() . $this->select();
                break;
            default:
                break;
        }
        // 分页字符串容器处理
        if ($this->wrap) {
            $pageWrap = $this->wrap;
            $pageWrapClass = $this->wrapClass ? " class=\"{$this->wrapClass}\"" : '';
            $pageWrapId = $this->wrapId ? " id=\"{$this->wrapId}\"" : '';
            $pageString = "<{$pageWrap}{$pageWrapClass}{$pageWrapId}>" . $pageString . "</{$pageWrap}>";
        }
        // 输出完整分页字符串
        return $pageString;
    }

    /**
     * 当前页码
     *
     * @return \Sfsn\Lib\unknown
     */
    public function getCurPage()
    {
        $config = $this->config;
        $url = $config['url'];
        $tag = $config['tag'];
        $separator = $config['separator'];
        $page = 1;
        if (isset($_GET[$tag])) {
            $page = intval($_GET[$tag]);
        }
        $page = max(1, $page);
        $this->current = $page;
        return $this->current;
    }

    private function _getUrl($page)
    {
        $config = $this->config;
        $url = $config['url'];
        $tag = $config['tag'];
        $separator = $config['separator'];
        if (isset($_GET[$tag])) {
            // 进行替换处理
            $pattern = $tag . '=(\d{0,})';
            $replace = $tag . '=' . $page;
            $url = preg_replace('/' . $pattern . '/i', $replace, $url);
        } else {
            $and = empty($_GET) ? '?' : '&';
            $url .= $and . $tag . '=' . $page;
        }
        return $url;
    }

    private function _getLink($page, $pageText = '', $style = '')
    {
        $text = empty($pageText) ? $page : $pageText;
        $style = empty($style) ? '' : 'class="' . $style . '"';
        $url = $this->_getUrl($page);
        if ($this->isAjax) {
            // 如果是使用AJAX模式
            return '<a ' . $style . ' href="javascript:' . $this->ajaxActionName . '(\'' . $url . '\')">' . $text . '</a>';
        } else {
            return '<a ' . $style . ' href="' . $url . '">' . $text . '</a>';
        }
    }
}